﻿
using System;
using System.Threading;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using System.Reflection;
using System.Deployment.Application;

namespace AppMain
{
    public partial class StartWindow : Form
    {
        // Testing Variables
        bool[] _oldTargetSwitchPositions = { false, false, false, false, false, false, false, false, false, false, false };
        byte[] _transferCounter = new byte[SwMatrix.NumberOfSupportedSwitches];
        // Singleton for Confirm Box
        ConfirmBox _confirmBox;
        //private Int16 _testingVar;
       
        //Parameters for Switch Matrix PLC
        string P_SwPLCIPAddress;
        int P_SwPlcScanTime;
        SwPlcComm _swPLC = new SwPlcComm();

        //Parameters for Burk PLC Control
        string P_BurkPLCIPAddress;
        int P_BurkPlcScanTime;
        BurkPlcComm _burkPLC = new BurkPlcComm();

        // Local Switch Control
        TxSwitcher txSwitcher;

        // Manual Switch Control
        ManualSwitchControl manControl;

        //Instance for writing logs from this file
        LogData log = AppMain.LogData.GetObject;
        int[] retryAttempts = new int[8];
        
        public StartWindow()
        {
            log.Write(string.Format("Started Application {0}", swVersion()));
            //Step 1: Init the GUI
            InitializeComponent();
            //Step 2: Init the Interface
            initInterface();
        }

        private void initInterface()
        {
            /******************************/
            /* Initialize the Application */
            /******************************/
            //Step 1: Read the settings file
            log.Write("Beginning to read Settings File...");
            SwPlcStatus.Text = "Beginning to read Settings File...";
            SwPlcStatus.ForeColor = Color.Black;
//            MeterPage.
            bool l_settingsReadSuccess = false;
            lblSettingsDisplay.Text = readSettings(ref l_settingsReadSuccess);
            log.Write(lblSettingsDisplay.Text);
            if (l_settingsReadSuccess == false)
            {
                SwPlcStatus.Text = "Settings file could not be read. Check log!";
                return;
            }

            // Switch Matrix PLC
            _swPLC.StartCommunication(P_SwPLCIPAddress, P_SwPlcScanTime);
            SwPlcStatus.Text = _swPLC.GetStatusText();

            // Burk PLC
            _burkPLC.StartCommunication(P_BurkPLCIPAddress, P_BurkPlcScanTime);
            BurkPlcStatus.Text = _burkPLC.GetStatusText();
            
            lblVersion.Text = PublishVersion;
            this.Text += " " + PublishVersion;

        }   //end void initInterface()

        private string readSettings(ref bool success_b)
        {
            //init success as false
            success_b = false;

            //New string for returning the results
            StringWriter settingstext = new StringWriter();
            settingstext.WriteLine("Settings loaded from file: SwitchMatrix.exe.config");

            foreach (string key in ConfigurationManager.AppSettings)
            {
                //Get the value of the parameter in the settings file
                string value = ConfigurationManager.AppSettings[key];
                //split the parameter name into an array using the '_' character
                string[] keysplit = key.Split('_');
                
                if (keysplit[0].Equals("SwMatrixPLC", StringComparison.CurrentCultureIgnoreCase))
                {
                    //Go here if the parameter is for the Switch Matrix PLC
                    if (keysplit[1].Equals("IPAddress", StringComparison.CurrentCultureIgnoreCase))
                    {
                        //This is the IP Address for the Switch Matrix PLC
                        P_SwPLCIPAddress = value;
                    }
                    else if (keysplit[1].Equals("ScanTime", StringComparison.CurrentCultureIgnoreCase))
                    {
                        //This is the PLC IP Address
                        P_SwPlcScanTime = Convert.ToInt32(value);
                    }
                    else
                    {
                        string error = string.Format("Error loading setting {0}", key);
                        return error;
                    }
                }
                else if (keysplit[0].Equals("BurkCommPLC", StringComparison.CurrentCultureIgnoreCase))
                {
                    //Go here if the parameter is for the Switch Matrix PLC
                    if (keysplit[1].Equals("IPAddress", StringComparison.CurrentCultureIgnoreCase))
                    {
                        //This is the IP Address for the Switch Matrix PLC
                        P_BurkPLCIPAddress = value;
                    }
                    else if (keysplit[1].Equals("ScanTime", StringComparison.CurrentCultureIgnoreCase))
                    {
                        //This is the PLC IP Address
                        P_BurkPlcScanTime = Convert.ToInt32(value);
                    }
                    else
                    {
                        string error = string.Format("Error loading setting {0}", key);
                        return error;
                    }
                }
                else if (keysplit[0].Equals("Transmitter", StringComparison.CurrentCultureIgnoreCase))
                {
                    //These are the colors for the transmitters
                    int index = 0;
                    try
                    {
                        index = Convert.ToInt32(keysplit[1]);
                    }
                    catch
                    {
                        string error = string.Format("Error loading setting {0}", key) + " Invalid Transmitter Number";
                    }
                    if (index > 8)
                    {
                        string error = string.Format("Error loading setting {0}", key) + " Only 7 Transmitters Supported";
                        // Will cause Subscript out of range error
                        //SwMatrix._txColor[index] = Color.SlateGray;
                    }
                    try
                    {
                        SwMatrix._txColor[index] = (Color.FromName(value));
                    }
                    catch
                    {
                        string error = string.Format("Error loading setting {0}", key) + " Invalid Color";
                        SwMatrix._txColor[index] = Color.SlateGray;
                        return error;
                    }
                    if (SwMatrix._txColor[index].ToArgb() == 0)
                    {
                        string error = string.Format("Error loading setting {0}", key) + " Invalid Color";
                        SwMatrix._txColor[index] = Color.SlateGray;
                    }
                }
                else if (keysplit[0].Equals("SwitchPosition", StringComparison.CurrentCultureIgnoreCase))
                {
                    //These are the image files for the switch positions
                    if (keysplit[1].Equals("0", StringComparison.CurrentCultureIgnoreCase))
                    {
                        if (System.IO.File.Exists(value))
                        {
                            SwMatrix.UpdateSwitchGraphicsLocations(SwMatrix.SwitchGraphic.Position0, Path.GetFullPath(value));
                        }
                        else
                        {
                            return string.Format("Error loading Switch Image File '{0}'", value);
                        }
                    }
                    else if (keysplit[1].Equals("1", StringComparison.CurrentCultureIgnoreCase))
                    {
                        if (System.IO.File.Exists(value))
                        {
                            SwMatrix.UpdateSwitchGraphicsLocations(SwMatrix.SwitchGraphic.Position1, Path.GetFullPath(value));
                        }
                        else
                        {
                            return string.Format("Error loading Switch Image File '{0}'", value);
                        }
                    }
                    else if (keysplit[1].Equals("Fault", StringComparison.CurrentCultureIgnoreCase))
                    {
                        if (System.IO.File.Exists(value))
                        {
                            SwMatrix.UpdateSwitchGraphicsLocations(SwMatrix.SwitchGraphic.PositionError, Path.GetFullPath(value));
                        }
                        else
                        {
                            return string.Format("Error loading Switch Image File '{0}'", value);
                        }
                    }
                    else if (keysplit[1].Equals("Moving", StringComparison.CurrentCultureIgnoreCase))
                    {
                        if (System.IO.File.Exists(value))
                        {
                            SwMatrix.UpdateSwitchGraphicsLocations(SwMatrix.SwitchGraphic.Moving, Path.GetFullPath(value));
                        }
                        else
                        {
                            return string.Format("Error loading Switch Image File '{0}'", value);
                        }
                    }
                    else if (keysplit[1].Equals("MoveTo0", StringComparison.CurrentCultureIgnoreCase))
                    {
                        if (System.IO.File.Exists(value))
                        {
                            SwMatrix.UpdateSwitchGraphicsLocations(SwMatrix.SwitchGraphic.ToPosition0, Path.GetFullPath(value));
                        }
                        else
                        {
                            return string.Format("Error loading Switch Image File '{0}'", value);
                        }
                    }
                    else if (keysplit[1].Equals("MoveTo1", StringComparison.CurrentCultureIgnoreCase))
                    {
                        if (System.IO.File.Exists(value))
                        {
                            SwMatrix.UpdateSwitchGraphicsLocations(SwMatrix.SwitchGraphic.ToPosition1, Path.GetFullPath(value));
                        }
                        else
                        {
                            return string.Format("Error loading Switch Image File '{0}'", value);
                        }
                    }
                }
                else if (keysplit[0].Equals("SwitchConfigurationFile", StringComparison.CurrentCultureIgnoreCase))
                {
                    SwMatrix.SwitchCombinationFileError error = SwMatrix.LoadSwitchCombinations(value);
                    switch (error)
                    {
                        case SwMatrix.SwitchCombinationFileError.BadFileName:
                        {
                            return string.Format("Error loading switch configuration File {0}", value);
                        }
                        case SwMatrix.SwitchCombinationFileError.BadTransmitterNumber:
                        {
                            return string.Format("Error loading Transmitter from Line {0} of switch configuration file {1}", SwMatrix._parseLineNumber.ToString(), value);
                        }
                        case SwMatrix.SwitchCombinationFileError.BadAntennaName:
                        {
                            return string.Format("Error loading Antenna from Line {0} of switch configuration file {1}", SwMatrix._parseLineNumber.ToString(), value);
                        }
                        case SwMatrix.SwitchCombinationFileError.BadSwitchNumber:
                        {
                            return string.Format("Error loading Switch from Line {0} of switch configuration file {1}", SwMatrix._parseLineNumber.ToString(), value);
                        }
                        case SwMatrix.SwitchCombinationFileError.UnexpectedCharacter:
                        {
                            return string.Format("Error loading Information from Line {0} of switch configuration file {1} - Unexpected Character", SwMatrix._parseLineNumber.ToString(), value);
                        }
                    }
                }
                else
                {
                    string error = string.Format("Error loading setting {0}", key);
                    return error;
                }
            }

            // Switch Matrix PLC
            if (P_SwPlcScanTime == 0)
            {
                string error = ("Switch Matrix PLC Scan Time not defined!");
                return error;
            }
            else
            {
                settingstext.WriteLine("Switch Matrix PLC Scan Time: {0} ms", P_SwPlcScanTime.ToString());
            }
            if (P_SwPLCIPAddress == null)
            {
                string error = ("Switch Matrix PLC IP Address not defined!");
                return error;
            }
            else
            {
                settingstext.WriteLine("Switch Matrix PLC IP Address: {0}", P_SwPLCIPAddress);
            }

            // Burk Communication PLC
            if (P_BurkPlcScanTime == 0)
            {
                string error = ("Burk Interface PLC Scan Time not defined!");
                return error;
            }
            else
            {
                settingstext.WriteLine("Burk Interface PLC Scan Time: {0} ms", P_BurkPlcScanTime.ToString());
            }
            if (P_BurkPLCIPAddress == null)
            {
                string error = ("Burk Interface PLC IP Address not defined!");
                return error;
            }
            else
            {
                settingstext.WriteLine("Burk Interface IP Address: {0}", P_BurkPLCIPAddress);
            } 

            //Settings were read successfully if it gets here
            success_b = true;
            return settingstext.ToString();     
        }


        private void StartWindow_FormClosed(object sender, FormClosedEventArgs e)
        {
            log.Write("Application closed");
            log.Close();
            if (SwMatrix._infoLog != null)
            {
                SwMatrix._infoLog.Close();
            }
            if (_swPLC._tmrScanPLC != null)
            {
                _swPLC._tmrScanPLC.Dispose();
            }
            if (txSwitcher != null)
            {
                if (txSwitcher._previewPane != null)
                {
                    txSwitcher._previewPane.Close();
                }
                txSwitcher.Close();
            }
            if (manControl != null)
            {
                manControl.Close();
            }
            // kill these 'newed' objects
        }

        private void btnRestart_Click(object sender, EventArgs e)
        {
            SwMatrix._resetPressed = true;
        }

        
        /// <summary>
        /// Return the current version. If running the deployed version, returns that version number,
        /// otherwise returns the assembly version.
        /// </summary>
        /// <returns>Version number</returns>
        private string swVersion()
        {
            string ourVersion = string.Empty;
            
            string assemName = Assembly.GetEntryAssembly().GetName().Name.ToString(); 
            //if running the deployed application, you can get the version
            //  from the ApplicationDeployment information. If you try
            //  to access this when you are running in Visual Studio, it will not work.
            
            if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
                ourVersion = ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString();
            else
            {
                System.Reflection.Assembly assemblyInfo = System.Reflection.Assembly.GetExecutingAssembly();
                if (assemblyInfo != null)
                    ourVersion = string.Format("{0} (Not Deployed)", assemblyInfo.GetName().Version.ToString());
            }
            return string.Format("{0} Version: {1}",assemName,ourVersion);
        }

        

        private void btnEditConfig_Click(object sender, EventArgs e)
        {
            string cfgFile = ".\\SwitchMatrix.exe.config";
            System.Diagnostics.Process.Start(@"notepad.exe", cfgFile);
        }

        
        private void btnShowLog_Click(object sender, EventArgs e)
        {
            string cfgFile = ".\\LogFiles";
            System.Diagnostics.Process.Start(@"explorer.exe", cfgFile);
        }

        private void TAT_Click(object sender, EventArgs e)
        {
            if (_confirmBox != null)
            {
                if (!_confirmBox.Visible)
                {
                    _confirmBox = new ConfirmBox(1);
                }
            }
            else
            {
                _confirmBox = new ConfirmBox(1);
            }
            _confirmBox.Show();
        }

        private void NRA_Click(object sender, EventArgs e)
        {
            if (_confirmBox != null)
            {
                if (!_confirmBox.Visible)
                {
                    _confirmBox = new ConfirmBox(0);
                }
            }
            else
            {
                _confirmBox = new ConfirmBox(0);
            }
            _confirmBox.Show();
        }

        private void TRT_Click(object sender, EventArgs e)
        {
            if (_confirmBox != null)
            {
                if (!_confirmBox.Visible)
                {
                    _confirmBox = new ConfirmBox(2);
                }
            }
            else
            {
                _confirmBox = new ConfirmBox(2);
            }
            _confirmBox.Show();
        }

        private void TIT_Click(object sender, EventArgs e)
        {
            if (_confirmBox != null)
            {
                if (!_confirmBox.Visible)
                {
                    _confirmBox = new ConfirmBox(3);
                }
            }
            else
            {
                _confirmBox = new ConfirmBox(3);
            }
            _confirmBox.Show();
        }

        public string PublishVersion
        {
            get
            {
                Assembly assem = Assembly.GetExecutingAssembly();
                AssemblyName assemName = assem.GetName();
                Version ver = assemName.Version;
                return string.Format("Version {0}.{1}.{2}.{3}", ver.Major, ver.Minor, ver.Build, ver.Revision);
            }
        }

        // This command Updates the SwitchMatrix Display
        private void SwitchMatrixTimer_Tick(object sender, EventArgs e)
        {
            // Only Update if the Switch Matrix Tab is active
            // Note: This may have to go away in the future, but
            // for now, it is only necessary to update the display when
            // it is active
            bool updateActive = true;
            // make sure that txSwitcher is defined before performing check for
            // preview pane.
            if (txSwitcher != null)
            {
                if (txSwitcher._previewPane != null)
                {
                    if (txSwitcher._previewPane.Visible)
                    {
                        updateActive = false;
                    }
                }
            }
            if (SwitchMatrix.Visible && updateActive)
            {
                //<KLUDGE>
                if (!_swPLC._modbusCommPortOpen && !_burkPLC._modbusCommPortOpen)
                {
                    SwMatrix.DetermineTransmittersToInhibit();
                }
                //</KLUDGE>
                Transmitter6.BackColor = SwMatrix._txColor[6];
                if (SwMatrix._inhibitedTransmitters[1])
                {
                    Transmitter6.BorderStyle = BorderStyle.FixedSingle;
                    Transmitter6.ForeColor = Color.Orange;
                }
                else
                {
                    Transmitter6.BorderStyle = BorderStyle.Fixed3D;
                    Transmitter6.ForeColor = Color.Black;
                }
                Transmitter8.BackColor = SwMatrix._txColor[8];
                if (SwMatrix._inhibitedTransmitters[3])
                {
                    Transmitter8.BorderStyle = BorderStyle.FixedSingle;
                    Transmitter8.ForeColor = Color.Orange;
                }
                else
                {
                    Transmitter8.BorderStyle = BorderStyle.Fixed3D;
                    Transmitter8.ForeColor = Color.Black;
                }
                Transmitter7.BackColor = SwMatrix._txColor[7];
                if (SwMatrix._inhibitedTransmitters[2])
                {
                    Transmitter7.BorderStyle = BorderStyle.FixedSingle;
                    Transmitter7.ForeColor = Color.Orange;
                }
                else
                {
                    Transmitter7.BorderStyle = BorderStyle.Fixed3D;
                    Transmitter7.ForeColor = Color.Black;
                }
                Transmitter5.BackColor = SwMatrix._txColor[5];
                if (SwMatrix._inhibitedTransmitters[0])
                {
                    Transmitter5.BorderStyle = BorderStyle.FixedSingle;
                    Transmitter5.ForeColor = Color.Orange;
                }
                else
                {
                    Transmitter5.BorderStyle = BorderStyle.Fixed3D;
                    Transmitter5.ForeColor = Color.Black;
                }
                TX6toSW2_1.BackColor = SwMatrix._txColor[6];
                TX6toSW2_2.BackColor = SwMatrix._txColor[6];
                TX8toSW2_1.BackColor = SwMatrix._txColor[8];
                TX8toSW2_2.BackColor = SwMatrix._txColor[8];
                TX8toSW2_3.BackColor = SwMatrix._txColor[8];
                TX7toSW1_1.BackColor = SwMatrix._txColor[7];
                TX7toSW1_2.BackColor = SwMatrix._txColor[7];
                TX5toSW1_1.BackColor = SwMatrix._txColor[5];
                // Only update this view if the preview pane is not open.
                if (txSwitcher == null)
                {
                    SwMatrix.CalculateTransmitterFeeds(SwMatrix._switchPositions, SwMatrix._switchPositions);
                }
                else
                {
                    if (txSwitcher._previewPane == null)
                    {
                        SwMatrix.CalculateTransmitterFeeds(SwMatrix._switchPositions, SwMatrix._switchPositions);
                    }
                    else
                    {
                        if (!txSwitcher._previewPane.Visible)
                        {
                            SwMatrix.CalculateTransmitterFeeds(SwMatrix._switchPositions, SwMatrix._switchPositions);
                        }
                    }
                }
                // track current Switch (makes copy/paste easier)
                byte currentSwitch = 0;
                // Switch 1 Outputs
                SW1toSW5_1.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 0)];
                SW1toSW5_2.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 0)];
                SW1toSW3_1.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 1)];
                Switch1.ImageLocation = SwMatrix._imageLocations[0];
                Switch1.Load();
                if (Switch1.Tag != null)
                {
                    if (Switch1.Tag.ToString() == "90")
                    {
                        Switch1.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);
                    }
                    if (Switch1.Tag.ToString() == "180")
                    {
                        Switch1.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
                    }
                    if (Switch1.Tag.ToString() == "270")
                    {
                        Switch1.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone);
                    }
                }
                // Switch 2 Outputs
                currentSwitch++;
                SW2toSW4_1.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 0)];
                SW2toSW3_1.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 1)];
                Switch2.ImageLocation = SwMatrix._imageLocations[1];
                Switch2.Load();
                if (Switch2.Tag != null)
                {
                    if(Switch2.Tag.ToString() == "90")
                    {
                        Switch2.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);
                    }
                    if (Switch2.Tag.ToString() == "180")
                    {
                        Switch2.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
                    }
                    if (Switch2.Tag.ToString() == "270")
                    {
                        Switch2.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone);
                    }
                }
                // Switch 3 Outputs
                currentSwitch++;
                SW3toSW4_1.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 0)];
                SW3toSW4_2.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 0)];
                SW3toSW4_3.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 0)];
                SW3toSW7_1.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 1)];
                Switch3.ImageLocation = SwMatrix._imageLocations[2];
                Switch3.Load();
                if (Switch3.Tag != null)
                {
                    if (Switch3.Tag.ToString() == "90")
                    {
                        Switch3.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);
                    }
                    if (Switch3.Tag.ToString() == "180")
                    {
                        Switch3.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
                    }
                    if (Switch3.Tag.ToString() == "270")
                    {
                        Switch3.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone);
                    }
                }
                // Switch 4 Outputs
                currentSwitch++;
                SW4toSW5_1.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 0)];
                SW4toSW5_2.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 0)];
                SW4toSW5_3.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 0)];
                SW4toSW5_4.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 0)];
                SW4toSW7_1.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 1)];
                Switch4.ImageLocation = SwMatrix._imageLocations[3];
                Switch4.Load();
                if (Switch4.Tag != null)
                {
                    if (Switch4.Tag.ToString() == "90")
                    {
                        Switch4.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);
                    }
                    if (Switch4.Tag.ToString() == "180")
                    {
                        Switch4.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
                    }
                    if (Switch4.Tag.ToString() == "270")
                    {
                        Switch4.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone);
                    }
                }
                // Switch 5 Outputs
                currentSwitch++;
                SW5toSW8_1.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 1)];
                SW5toSW6_1.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 0)];
                SW5toSW6_2.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 0)];
                Switch5.ImageLocation = SwMatrix._imageLocations[4];
                Switch5.Load();
                if (Switch5.Tag != null)
                {
                    if (Switch5.Tag.ToString() == "90")
                    {
                        Switch5.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);
                    }
                    if (Switch5.Tag.ToString() == "180")
                    {
                        Switch5.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
                    }
                    if (Switch5.Tag.ToString() == "270")
                    {
                        Switch5.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone);
                    }
                }
                // Switch 6 Outputs
                currentSwitch++;
                SW6toANT4_1.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 0)];
                SW6toANT4_2.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 0)];
                SW6toANT1_1.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 1)];
                Switch6.ImageLocation = SwMatrix._imageLocations[5];
                Switch6.Load();
                if (Switch6.Tag != null)
                {
                    if (Switch6.Tag.ToString() == "90")
                    {
                        Switch6.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);
                    }
                    if (Switch6.Tag.ToString() == "180")
                    {
                        Switch6.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
                    }
                    if (Switch6.Tag.ToString() == "270")
                    {
                        Switch6.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone);
                    }
                }
                // Switch 7 Outputs
                currentSwitch++;
                SW7toSW6_1.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 0)];
                SW7toSW6_2.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 0)];
                SW7toSW6_3.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 0)];
                SW7toSW10_1.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 1)];
                Switch7.ImageLocation = SwMatrix._imageLocations[6];
                Switch7.Load();
                if (Switch7.Tag != null)
                {
                    if (Switch7.Tag.ToString() == "90")
                    {
                        Switch7.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);
                    }
                    if (Switch7.Tag.ToString() == "180")
                    {
                        Switch7.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
                    }
                    if (Switch7.Tag.ToString() == "270")
                    {
                        Switch7.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone);
                    }
                }
                // Switch 8 Outputs
                currentSwitch++;
                SW8toANT2B_1.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 0)];
                SW8toANT2B_2.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 0)];
                SW8toANT2A_1.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 1)];
                Switch8.ImageLocation = SwMatrix._imageLocations[7];
                Switch8.Load();
                if (Switch8.Tag != null)
                {
                    if (Switch8.Tag.ToString() == "90")
                    {
                        Switch8.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);
                    }
                    if (Switch8.Tag.ToString() == "180")
                    {
                        Switch8.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
                    }
                    if (Switch8.Tag.ToString() == "270")
                    {
                        Switch8.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone);
                    }
                }
                // Switch 9 Outputs
                currentSwitch++;
                SW9toLOAD_1.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 0)];
                SW9toLOAD_2.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 0)];
                SW9toANT3_1.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 1)];
                Switch9.ImageLocation = SwMatrix._imageLocations[8];
                Switch9.Load();
                if (Switch9.Tag != null)
                {
                    if (Switch9.Tag.ToString() == "90")
                    {
                        Switch9.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);
                    }
                    if (Switch9.Tag.ToString() == "180")
                    {
                        Switch9.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
                    }
                    if (Switch9.Tag.ToString() == "270")
                    {
                        Switch9.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone);
                    }
                }
                // Switch 10 Outputs
                currentSwitch++;
                SW10toANT5_1.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 0)];
                SW10toSW9_1.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingSegment(currentSwitch, 1)];
                Switch10.ImageLocation = SwMatrix._imageLocations[9];
                Switch10.Load();
                if (Switch10.Tag != null)
                {
                    if (Switch10.Tag.ToString() == "90")
                    {
                        Switch10.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);
                    }
                    if (Switch10.Tag.ToString() == "180")
                    {
                        Switch10.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
                    }
                    if (Switch10.Tag.ToString() == "270")
                    {
                        Switch10.Image.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone);
                    }
                }
                // Antennas
                Antenna1.BackColor =  SwMatrix._txColor[SwMatrix.TransmitterFeedingAntenna(0)];
                Antenna2A.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingAntenna(1)];
                Antenna2B.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingAntenna(2)];
                Antenna3.BackColor =  SwMatrix._txColor[SwMatrix.TransmitterFeedingAntenna(3)];
                Antenna4.BackColor =  SwMatrix._txColor[SwMatrix.TransmitterFeedingAntenna(4)];
                Antenna5.BackColor =  SwMatrix._txColor[SwMatrix.TransmitterFeedingAntenna(5)];
                DummyLoad.BackColor = SwMatrix._txColor[SwMatrix.TransmitterFeedingAntenna(6)];
                if (SwMatrix._unreadyAntennas[0])
                {
                    Antenna1.BorderStyle = BorderStyle.FixedSingle;
                    Antenna1.ForeColor = Color.Orange;
                }
                else
                {
                    Antenna1.BorderStyle = BorderStyle.Fixed3D;
                    Antenna1.ForeColor = Color.White;
                }
                if (SwMatrix._unreadyAntennas[1])
                {
                    Antenna2A.BorderStyle = BorderStyle.FixedSingle;
                    Antenna2A.ForeColor = Color.Orange;
                }
                else
                {
                    Antenna2A.BorderStyle = BorderStyle.Fixed3D;
                    Antenna2A.ForeColor = Color.White;
                }
                if (SwMatrix._unreadyAntennas[2])
                {
                    Antenna2B.BorderStyle = BorderStyle.FixedSingle;
                    Antenna2B.ForeColor = Color.Orange;
                }
                else
                {
                    Antenna2B.BorderStyle = BorderStyle.Fixed3D;
                    Antenna2B.ForeColor = Color.White;
                }
                if (SwMatrix._unreadyAntennas[3])
                {
                    Antenna3.BorderStyle = BorderStyle.FixedSingle;
                    Antenna3.ForeColor = Color.Orange;
                }
                else
                {
                    Antenna3.BorderStyle = BorderStyle.Fixed3D;
                    Antenna3.ForeColor = Color.White;
                }
                if (SwMatrix._unreadyAntennas[4])
                {
                    Antenna4.BorderStyle = BorderStyle.FixedSingle;
                    Antenna4.ForeColor = Color.Orange;
                }
                else
                {
                    Antenna4.BorderStyle = BorderStyle.Fixed3D;
                    Antenna4.ForeColor = Color.White;
                }
                if (SwMatrix._unreadyAntennas[5])
                {
                    Antenna5.BorderStyle = BorderStyle.FixedSingle;
                    Antenna5.ForeColor = Color.Orange;
                }
                else
                {
                    Antenna5.BorderStyle = BorderStyle.Fixed3D;
                    Antenna5.ForeColor = Color.White;
                }
                if (SwMatrix._unreadyAntennas[6])
                {
                    DummyLoad.BorderStyle = BorderStyle.FixedSingle;
                    DummyLoad.ForeColor = Color.Orange;
                }
                else
                {
                    DummyLoad.BorderStyle = BorderStyle.Fixed3D;
                    DummyLoad.ForeColor = Color.White;
                }
                Fault1.Visible = SwMatrix._switchError[0];
                Fault2.Visible = SwMatrix._switchError[1];
                Fault3.Visible = SwMatrix._switchError[2];
                Fault4.Visible = SwMatrix._switchError[3];
                Fault5.Visible = SwMatrix._switchError[4];
                Fault6.Visible = SwMatrix._switchError[5];
                Fault7.Visible = SwMatrix._switchError[6];
                Fault8.Visible = SwMatrix._switchError[7];
                Fault9.Visible = SwMatrix._switchError[8];
                Fault10.Visible = SwMatrix._switchError[9];

                TX5_Locked.Visible = SwMatrix._transmitterLocked[5];
                TX6_Locked.Visible = SwMatrix._transmitterLocked[6];
                TX7_Locked.Visible = SwMatrix._transmitterLocked[7];
                TX8_Locked.Visible = SwMatrix._transmitterLocked[8];

                //<KLUDGE>
                if (_burkPLC._modbusReadPending)
                {
                    BurkReadPending.Text = "True";
                }
                else
                {
                    BurkReadPending.Text = "False";
                }

                if(_swPLC._modbusReadPending)
                {
                    FieldMatrixReadPending.Text = "True";
                }
                else
                {
                    FieldMatrixReadPending.Text = "False";
                }

                if (SwMatrix._transferInitiated)
                {
                    XfrInit.Text = "True";
                }
                else
                {
                    XfrInit.Text = "False";
                }
                if (SwMatrix._dataVerified)
                {
                    DataVer.Text = "True";
                }
                else
                {
                    DataVer.Text = "False";
                }
                if (SwMatrix._transferActive)
                {
                    XfrAct.Text = "True";
                }
                else
                {
                    XfrAct.Text = "False";
                }
                if (SwMatrix._transferSent)
                {
                    XfrSent.Text = "True";
                }
                else
                {
                    XfrSent.Text = "False";
                }
                if (SwMatrix._transferComplete)
                {
                    XfrComp.Text = "True";
                }
                else
                {
                    XfrComp.Text = "False";
                }

            }
            else if (Settings.Visible)
            {
                double temp = SwMatrix._dataToBeWritten[0];
                NRA.Text = temp.ToString("#0");
                temp = SwMatrix._dataToBeWritten[1];
                temp /= 10.0;
                TAT.Text = temp.ToString("##0.0") + " sec";
                temp = SwMatrix._dataToBeWritten[2];
                temp /= 10.0;
                TRT.Text = temp.ToString("##0.0") + " sec";
                temp = SwMatrix._dataToBeWritten[3];
                temp /= 10.0;
                TIT.Text = temp.ToString("##0.0") + " sec";
                //log.Write("This Info Should appear in the log.");
            }
            SwPlcStatus.ForeColor = _swPLC._guiTextForeColor;
            SwPlcStatus.Text = _swPLC._guiText;
            BurkPlcStatus.ForeColor = _burkPLC._guiTextForeColor;
            BurkPlcStatus.Text = _burkPLC._guiText;

            // Note: This code allows for simulation without a connection to the PLC
            // it does permit updating the switch status based on desired configuration
            // and is required to allow the simulation to operate as planned.
            // <SIMULATION TOOL>            
            if(!_swPLC._modbusCommPortOpen)
            {
                bool transferActive = false;
                for (byte x = 0; x < SwMatrix.NumberOfSupportedSwitches; x++)
                {
                    if (SwMatrix._targetSwitchPositions[x] != _oldTargetSwitchPositions[x])
                    {
                        SwMatrix._switchPositions[x] = (byte)SwMatrix.SwitchGraphic.Moving;
                        _transferCounter[x]++;
                        transferActive = true;
                        SwMatrix._dataVerified = true;
                        SwMatrix._transferInitiated = false;
                    }
                    if (_transferCounter[x] >= 10) // 10 seconds
                    {
                        _oldTargetSwitchPositions[x] = SwMatrix._targetSwitchPositions[x];
                        if (SwMatrix._targetSwitchPositions[x])
                        {
                            SwMatrix._switchPositions[x] = (byte)SwMatrix.SwitchGraphic.Position1;
                        }
                        else
                        {
                            SwMatrix._switchPositions[x] = (byte)SwMatrix.SwitchGraphic.Position0;
                        }
                        _transferCounter[x] = 0;
                    }
                }
                if (transferActive && !SwMatrix._transferActive)
                {
                    SwMatrix._transferComplete = true;
                }
                SwMatrix._transferActive = transferActive;
            }
            // </SIMULATION TOOL>

            //Update Flasher
            if (Flasher.BackColor == System.Drawing.SystemColors.Control)
            {
                Flasher.BackColor = Color.LightGreen;
            }
            else
            {
                Flasher.BackColor = System.Drawing.SystemColors.Control;
            }
        }

        // This logic allows updating the perceived switch position to reflect the
        // position selected by the user by clicking on the boxes.
        private void Switch1_Click(object sender, EventArgs e)
        {
            if (!_swPLC._modbusCommPortOpen)
            {
                if (SwMatrix._switchPositions[0] > 1)
                {
                    SwMatrix._switchPositions[0] = 0;
                }
                else
                {
                    SwMatrix._switchPositions[0]++;
                }
            }
        }

        private void Switch2_Click(object sender, EventArgs e)
        {
            if (!_swPLC._modbusCommPortOpen)
            {
                if (SwMatrix._switchPositions[1] > 1)
                {
                    SwMatrix._switchPositions[1] = 0;
                }
                else
                {
                    SwMatrix._switchPositions[1]++;
                }
            }
        }

        private void Switch3_Click(object sender, EventArgs e)
        {
            if (!_swPLC._modbusCommPortOpen)
            {
                if (SwMatrix._switchPositions[2] > 1)
                {
                    SwMatrix._switchPositions[2] = 0;
                }
                else
                {
                    SwMatrix._switchPositions[2]++;
                }
            }
        }

        private void Switch4_Click(object sender, EventArgs e)
        {
            if (!_swPLC._modbusCommPortOpen)
            {
                if (SwMatrix._switchPositions[3] > 1)
                {
                    SwMatrix._switchPositions[3] = 0;
                }
                else
                {
                    SwMatrix._switchPositions[3]++;
                }
            }
        }

        private void Switch5_Click(object sender, EventArgs e)
        {
            if (!_swPLC._modbusCommPortOpen)
            {
                if (SwMatrix._switchPositions[4] > 1)
                {
                    SwMatrix._switchPositions[4] = 0;
                }
                else
                {
                    SwMatrix._switchPositions[4]++;
                }
            }
        }

        private void Switch6_Click(object sender, EventArgs e)
        {
            if (!_swPLC._modbusCommPortOpen)
            {
                if (SwMatrix._switchPositions[5] > 1)
                {
                    SwMatrix._switchPositions[5] = 0;
                }
                else
                {
                    SwMatrix._switchPositions[5]++;
                }
            }
        }

        private void Switch7_Click(object sender, EventArgs e)
        {
            if (!_swPLC._modbusCommPortOpen)
            {
                if (SwMatrix._switchPositions[6] > 1)
                {
                    SwMatrix._switchPositions[6] = 0;
                }
                else
                {
                    SwMatrix._switchPositions[6]++;
                }
            }
        }

        private void Switch8_Click(object sender, EventArgs e)
        {
            if (!_swPLC._modbusCommPortOpen)
            {
                if (SwMatrix._switchPositions[7] > 1)
                {
                    SwMatrix._switchPositions[7] = 0;
                }
                else
                {
                    SwMatrix._switchPositions[7]++;
                }
            }
        }

        private void Switch9_Click(object sender, EventArgs e)
        {
            if (!_swPLC._modbusCommPortOpen)
            {
                if (SwMatrix._switchPositions[8] > 1)
                {
                    SwMatrix._switchPositions[8] = 0;
                }
                else
                {
                    SwMatrix._switchPositions[8]++;
                }
            }
        }

        private void Switch10_Click(object sender, EventArgs e)
        {
            if (!_swPLC._modbusCommPortOpen)
            {
                if (SwMatrix._switchPositions[9] > 1)
                {
                    SwMatrix._switchPositions[9] = 0;
                }
                else
                {
                    SwMatrix._switchPositions[9]++;
                }
            }
        }
        //</KLUDGE>
//#endif
        private void CfgTxSettings_Click(object sender, EventArgs e)
        {
            txSwitcher = new TxSwitcher();
            // Update Data for actual Switch Position
            SwMatrix.CalculateTransmitterFeeds(SwMatrix._switchPositions, SwMatrix._switchPositions);
            // Necessary for Antenna Status to be accurate
            SwMatrix.CalculateRealTransmitterFeeds(SwMatrix._switchPositions);

            // Update Antenna Configuration to Default
            for (byte x = 0; x <= SwMatrix.MaximumTransmitterNumber; x++)
            {
                SwMatrix._antennaSelected[x] = SwMatrix._antennaConnected[x];
            }

            // Testing Software
            if (!_swPLC._modbusCommPortOpen)
            {
                for (byte x = 0; x < SwMatrix.NumberOfSupportedSwitches; x++)
                {
                    _oldTargetSwitchPositions[x] = (SwMatrix._switchPositions[x] > 0);
                    SwMatrix._targetSwitchPositions[x] = (SwMatrix._switchPositions[x] > 0);
                }
            }

            txSwitcher.UpdateCheckBoxes();

            //txSwitcher.UpdateDisplay = UpdateConfigDisplay;
            txSwitcher.ShowDialog();
        }

        private void StartWindow_Load(object sender, EventArgs e)
        {

        }

        private void ManualControl_Click(object sender, EventArgs e)
        {
            manControl = new ManualSwitchControl();
            // Update Data for actual Switch Position
            for (byte x = 0; x < AppMain.SwMatrix.NumberOfSupportedSwitches; x++)
            {
                manControl._manualSwitchPositions[x] = AppMain.SwMatrix._switchPositions[x];
                if (!_swPLC._modbusCommPortOpen)
                {
                    if (AppMain.SwMatrix._switchPositions[x] > 0)
                    {
                        _oldTargetSwitchPositions[x] = true;
                        SwMatrix._targetSwitchPositions[x] = true;
                    }
                    else
                    {
                        _oldTargetSwitchPositions[x] = false;
                        SwMatrix._targetSwitchPositions[x] = false;
                    }
                }
            }
            // Start with previous update from Burk or other screen
            manControl.ShowDialog();
        }

        private void Antenna1_Click(object sender, EventArgs e)
        {
            if (!_burkPLC._modbusCommPortOpen)
            {
                SwMatrix._unreadyAntennas[0] = !SwMatrix._unreadyAntennas[0]; 
            }
        }

        private void Antenna2A_Click(object sender, EventArgs e)
        {
            if (!_burkPLC._modbusCommPortOpen)
            {
                SwMatrix._unreadyAntennas[1] = !SwMatrix._unreadyAntennas[1];
            }
        }

        private void Antenna2B_Click(object sender, EventArgs e)
        {
            if (!_burkPLC._modbusCommPortOpen)
            {
                SwMatrix._unreadyAntennas[2] = !SwMatrix._unreadyAntennas[2];
            }
        }

        private void Antenna3_Click(object sender, EventArgs e)
        {
            if (!_burkPLC._modbusCommPortOpen)
            {
                SwMatrix._unreadyAntennas[3] = !SwMatrix._unreadyAntennas[3];
            }
        }

        private void Antenna4_Click(object sender, EventArgs e)
        {
            if (!_burkPLC._modbusCommPortOpen)
            {
                SwMatrix._unreadyAntennas[4] = !SwMatrix._unreadyAntennas[4];
            }
        }

        private void Antenna5_Click(object sender, EventArgs e)
        {
            if (!_burkPLC._modbusCommPortOpen)
            {
                SwMatrix._unreadyAntennas[5] = !SwMatrix._unreadyAntennas[5];
            }
        }

        private void DummyLoad_Click(object sender, EventArgs e)
        {
            if (!_burkPLC._modbusCommPortOpen)
            {
                SwMatrix._unreadyAntennas[6] = !SwMatrix._unreadyAntennas[6];
            }
        }
    }
}

